//
//  AuothViewController.swift
//  ZBWb
//
//  Created by 天隐翎 on 16/4/11.
//  Copyright © 2016年 csdn. All rights reserved.
//

import UIKit
//提示框第三方框架
import SVProgressHUD

private let userInfokey = "com.itheima.userifonKey"

class AuothViewController: UIViewController {

//    添加webView
    let webView = UIWebView()
    override func loadView() {
//        webView.backgroundColor = UIColor.redColor()
        
        view = webView
        
        webView.delegate = self
    }
    
//    视图即将消失
    
    override func viewDidDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: "closeit")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoAddInfo")
//        使用创建的WebView去加载页面
        let urlstring = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + "1033632904" + "&redirect_uri=" + "http://www.itheima.com"
        let  url = NSURL(string: urlstring)
//        设置请求
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
    }
//    点击事件
    @objc private func closeit(){
        dismissViewControllerAnimated(true, completion: nil)
        
    }
//    点击事件
    @objc private func autoAddInfo(){

    webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'zhangbin19912@sina.cn', document.getElementById('passwd').value = 'woaiyx1314' ")
//
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
}

//MARK--UIwebView的代理方法
extension AuothViewController:UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
//        开启等待指示器
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
//        关闭用户的等待指示器
        let webTitle = webView.stringByEvaluatingJavaScriptFromString("document.title")
        title = webTitle
        
        SVProgressHUD.dismiss()
    }
//    授权成功后,获取code
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString ?? ""
        let flag = "code="
        if urlString.containsString(flag){
            let range = urlString.rangeOfString(flag)!
            let code = urlString.substringFromIndex(range.endIndex)
            print(code)
//            使用授权码,请求accesstoken
//            loadcode(code)
//            调用ViewModel中的方法
            ZBuserInfoModelViewOuath.shareInfoModelViewOuath.loadcode(code, finished: { (isSuccess) -> () in
                if !isSuccess{
                    SVProgressHUD.showErrorWithStatus("登录失败")
                }
                    SVProgressHUD.showSuccessWithStatus("登录成功")
                
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                   
//                    UIApplication.sharedApplication().keyWindow?.rootViewController = MainTabBarViewController()
                    NSNotificationCenter.defaultCenter().postNotificationName(ZBSwitchRootViewController, object: nil)
                    
                })
            })
            return false
        }
       return true
    }
//使用授权码,请求accesstoken
//    private func loadcode(code:String) {
//        let url = "https://api.weibo.com/oauth2/access_token"
//        
////        设置参数
//        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type": "authorization_code","code":code,"redirect_uri":redirect_uri]
////        事先封装好的请求方法
//        ZBNetWorkTool.sharedTools.request(.POST, urlString: url, parameters: parameters) { (result, error) -> () in
//            
//            if error != nil{
//                print(error)
//                SVProgressHUD.showErrorWithStatus("出错误了")
//                return
//            }
//            print("授权成功")
//            print(result)
//            
////            授权成功,在请求成功的回调中,再去获取用户信息
//            self.loadViewInfo(result!)
//        }
//        
//        
//    }
//    
////    使用token获取用户信息
//    private  func loadViewInfo(result: AnyObject) {
//        //尝试将AnyObject转换为字典
//        guard let dict = result as? [String: AnyObject] else {
//            SVProgressHUD.showErrorWithStatus("数据错误")
//            return
//            
//        }
//        let token = dict["access_token"]!
//        let uid = dict["uid"]!
//        
////        在result中获取token,uid
//        let urlString = "https://api.weibo.com/2/users/show.json"
////        字典数组中不能添加为nil
//        let parameters = ["access_token": token, "uid": uid]
//        
//        ZBNetWorkTool.sharedTools.request(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
//            if error != nil {
//                print(error)
//                SVProgressHUD.showErrorWithStatus("世界上最遥远的距离就是没有网络")
//                return
//            }
//            print("获取用户信息成功")
//            print(result)
//            
//            
////            将AnyObject转换为字典类型
//            guard var userInfodic = result as? [String : AnyObject] else {
//                SVProgressHUD.showErrorWithStatus("数据结构错误")
//                return
//  
//            }
////            合并字典
//            for(k,v) in dict{
//                userInfodic[k] = v
//                
//            }
//            print(userInfodic)
////           偏好设置
//            let userDefauls = NSUserDefaults.standardUserDefaults()
////            字典转模型
//            let account = ZBuserAccount(dict: userInfodic)
////            获得模型对象字典模型对象
//            let keys = ["access_token","avatar_large","name","expires_in","uid"]
//            
//            let accountDict = account.dictionaryWithValuesForKeys(keys)
//            
////            将对象保存到偏好设置中
//            userDefauls.setObject(accountDict, forKey: userInfokey)
//            
////            同步
//            userDefauls.synchronize()
//
//            print(NSHomeDirectory())
//        }
// 
//    }
//   
}













